<template>
  <div class="app-container">
    <!-- 搜索和操作栏 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或姓名"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </el-col>
      <el-col :span="16" class="text-right">
        <el-button type="primary" @click="handleAdd">新增账号</el-button>
      </el-col>
    </el-row>

    <!-- 用户表格 -->
    <el-table :data="filteredUsers" border style="width: 100%">
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="fullname" label="姓名" width="150" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="roleTagType[row.role]">
            {{ roleMap[row.role] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑账号' : '新增账号'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="姓名" prop="fullname">
          <el-input v-model="formData.fullname" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据
const users = ref([
  { id: 1, username: 'admin', fullname: '管理员', role: 'admin', status: 1 },
  { id: 2, username: 'editor1', fullname: '张三', role: 'editor', status: 1 },
  { id: 3, username: 'viewer1', fullname: '李四', role: 'viewer', status: 0 }
])

const roleMap = {
  admin: '管理员',
  editor: '编辑',
  viewer: '查看者'
}

const roleTagType = {
  admin: 'danger',
  editor: 'warning',
  viewer: 'success'
}

const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'editor', label: '编辑' },
  { value: 'viewer', label: '查看者' }
]

// 搜索功能
const searchKeyword = ref('')
const filteredUsers = computed(() => {
  return users.value.filter(
    (user) =>
      user.username.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      user.fullname.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const formData = ref({
  id: null,
  username: '',
  fullname: '',
  role: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const validatePassword = (rule, value, callback) => {
  if (!isEdit.value && !value) {
    callback(new Error('请输入密码'))
  } else if (formData.value.password !== formData.value.confirmPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '长度在3到12个字符', trigger: 'blur' }
  ],
  fullname: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在2到6个字符', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePassword, trigger: 'blur' }]
}

// 操作方法
const handleSearch = () => {
  // 实际项目中这里可以调用API
}

const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    id: null,
    username: '',
    fullname: '',
    role: '',
    password: '',
    confirmPassword: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row, password: '', confirmPassword: '' }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      users.value = users.value.filter((user) => user.id !== row.id)
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

const handleStatusChange = (row) => {
  ElMessage.success(`已${row.status ? '启用' : '禁用'} ${row.username}`)
}

const handleSubmit = async () => {
  await formRef.value.validate()
  
  if (isEdit.value) {
    // 更新逻辑
    const index = users.value.findIndex((user) => user.id === formData.value.id)
    users.value[index] = {
      ...formData.value,
      // 实际应在前端加密或调用后端接口处理密码
      password: formData.value.password || users.value[index].password
    }
  } else {
    // 新增逻辑
    users.value.push({
      ...formData.value,
      id: Date.now(),
      status: 1
    })
  }
  
  dialogVisible.value = false
  ElMessage.success('操作成功')
}

onMounted(() => {
  // 这里可以初始化加载数据
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb-4 {
  margin-bottom: 1rem;
}
.text-right {
  text-align: right;
}
</style>